<template>
  <div class="experiment-manager">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card title="实验管理">
          <template #header>
            <span>实验管理</span>
            <el-button type="primary" @click="showCreateDialog" style="float: right;">
              <el-icon><Plus /></el-icon>
              创建实验
            </el-button>
          </template>
          
          <el-table :data="experiments" stripe>
            <el-table-column prop="experiment_id" label="实验ID" width="150" />
            <el-table-column prop="course_name" label="课程名称" width="200" />
            <el-table-column prop="user_id" label="用户ID" width="150" />
            <el-table-column prop="status" label="状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)" size="small">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="created_time" label="创建时间" width="180" />
            <el-table-column label="操作" width="250">
              <template #default="scope">
                <el-space>
                  <el-button 
                    size="small" 
                    type="primary" 
                    @click="openExperiment(scope.row)"
                  >
                    打开实验
                  </el-button>
                  <el-button 
                    size="small" 
                    type="warning" 
                    @click="stopExperiment(scope.row.experiment_id)"
                  >
                    停止
                  </el-button>
                  <el-button 
                    size="small" 
                    type="danger" 
                    @click="deleteExperiment(scope.row.experiment_id)"
                  >
                    删除
                  </el-button>
                </el-space>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 创建实验对话框 -->
    <el-dialog v-model="createDialog.visible" title="创建新实验" width="500px">
      <el-form :model="createDialog.form" label-width="100px">
        <el-form-item label="实验ID" required>
          <el-input v-model="createDialog.form.experiment_id" placeholder="输入实验ID" />
        </el-form-item>
        <el-form-item label="课程名称" required>
          <el-input v-model="createDialog.form.course_name" placeholder="输入课程名称" />
        </el-form-item>
        <el-form-item label="用户ID" required>
          <el-input v-model="createDialog.form.user_id" placeholder="输入用户ID" />
        </el-form-item>
        <el-form-item label="课程类型">
          <el-select v-model="createDialog.form.course_type" placeholder="选择课程类型">
            <el-option label="Python编程" value="python" />
            <el-option label="数据科学" value="datascience" />
            <el-option label="机器学习" value="ml" />
            <el-option label="Web开发" value="web" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="createDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="createExperiment" :loading="creating">
          {{ creating ? '创建中...' : '创建实验' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'ExperimentManager',
  setup() {
    const experiments = ref([
      {
        experiment_id: 'exp001',
        course_name: 'Python基础',
        user_id: 'student001',
        status: 'running',
        created_time: '2024-01-15 10:30:00',
        url: 'http://192.168.31.114:5173/?folder=/home/mobox/course/student001/Python基础/exp001'
      },
      {
        experiment_id: 'exp002',
        course_name: '数据科学入门',
        user_id: 'student002',
        status: 'stopped',
        created_time: '2024-01-14 15:20:00',
        url: null
      }
    ])
    
    const createDialog = reactive({
      visible: false,
      form: {
        experiment_id: '',
        course_name: '',
        user_id: '',
        course_type: 'python'
      }
    })
    
    const creating = ref(false)
    
    const getStatusType = (status) => {
      const statusMap = {
        'running': 'success',
        'stopped': 'info',
        'error': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    const showCreateDialog = () => {
      // 重置表单
      Object.assign(createDialog.form, {
        experiment_id: '',
        course_name: '',
        user_id: '',
        course_type: 'python'
      })
      createDialog.visible = true
    }
    
    const createExperiment = async () => {
      // 验证表单
      if (!createDialog.form.experiment_id || !createDialog.form.course_name || !createDialog.form.user_id) {
        ElMessage.warning('请填写所有必需字段')
        return
      }
      
      creating.value = true
      
      try {
        const response = await axios.post('/api/experiment/resource', createDialog.form)
        
        // 添加到实验列表
        experiments.value.unshift({
          ...createDialog.form,
          status: 'running',
          created_time: new Date().toLocaleString(),
          url: response.data.data.url
        })
        
        ElMessage.success('实验创建成功')
        createDialog.visible = false
        
      } catch (error) {
        console.error('创建实验失败:', error)
        ElMessage.error('创建实验失败')
      } finally {
        creating.value = false
      }
    }
    
    const openExperiment = (experiment) => {
      if (experiment.url) {
        window.open(experiment.url, '_blank')
      } else {
        ElMessage.warning('实验环境未准备就绪')
      }
    }
    
    const stopExperiment = async (experimentId) => {
      try {
        await axios.post(`/api/experiment/docker/stop`, { experiment_id: experimentId })
        
        // 更新状态
        const experiment = experiments.value.find(exp => exp.experiment_id === experimentId)
        if (experiment) {
          experiment.status = 'stopped'
          experiment.url = null
        }
        
        ElMessage.success('实验已停止')
      } catch (error) {
        console.error('停止实验失败:', error)
        ElMessage.error('停止实验失败')
      }
    }
    
    const deleteExperiment = async (experimentId) => {
      try {
        await ElMessageBox.confirm('确定要删除此实验吗？', '删除确认', { type: 'warning' })
        
        // 从列表中移除
        const index = experiments.value.findIndex(exp => exp.experiment_id === experimentId)
        if (index !== -1) {
          experiments.value.splice(index, 1)
        }
        
        ElMessage.success('实验已删除')
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除实验失败:', error)
          ElMessage.error('删除实验失败')
        }
      }
    }
    
    const refreshExperiments = async () => {
      try {
        const response = await axios.get('/api/experiment/list')
        
        // 根据后端API的响应格式处理数据
        if (response.data && response.data.data) {
          experiments.value = response.data.data
        } else if (Array.isArray(response.data)) {
        experiments.value = response.data
        } else {
          console.warn('意外的API响应格式:', response.data)
          experiments.value = []
        }
      } catch (error) {
        console.error('获取实验列表失败:', error)
        // 如果API调用失败，保持使用默认的模拟数据
        // 这样前端不会完全空白
      }
    }
    
    onMounted(() => {
      refreshExperiments()
    })
    
    return {
      experiments,
      createDialog,
      creating,
      getStatusType,
      showCreateDialog,
      createExperiment,
      openExperiment,
      stopExperiment,
      deleteExperiment
    }
  }
}
</script>

<style scoped>
.experiment-manager {
  padding: 0;
}
</style> 